package com.musicsonar.android.activity;

import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.musicsonar.android.adapter.ResultSearchAdapter;
import com.musicsonar.android.bean.PlayList;
import com.musicsonar.android.menu.IconContextMenu;
import com.musicsonar.android.utils.MusicSonarConstant;
import com.musicsonar.android.utils.MusicSonarUtils;
import com.musicsonar.android.utils.SongsManager;

@SuppressWarnings("deprecation")
public class TabPlayListActivity extends TabActivity implements OnLongClickListener, OnTabChangeListener{

	private static TabPlayListActivity me;

	private static Dialog dialog;

	private ImageButton btnSearch;
	private LinearLayout btnBack;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.tab_playlist);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.header_playlist);

		btnSearch = (ImageButton) findViewById(R.id.btnSearch);
		btnSearch.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				Intent i = new Intent(getApplicationContext(), SearchActivity.class);
				startActivityForResult(i, 100);
			}
		});

		btnBack = (LinearLayout) findViewById(R.id.back_playlist_header);
		btnBack.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
		        Log.d("CDA", "onBackPressed Called");
		        Intent intent = new Intent(me.getApplicationContext(), MusicSonarActivity.class);
		        setResult(0, intent);
		        finish();
			}
		});

		me = this;

		List<PlayList> list = SongsManager.getPlayList();

		Resources res = getResources(); // Resource object to get Drawables
		TabHost tabHost = getTabHost();  // The activity TabHost
		TabWidget tabWidget = getTabWidget();
		TabHost.TabSpec spec;  // Resusable TabSpec for each tab
		Intent intent;  // Reusable Intent for each tab

		int tabSelected = 0;

		for(int i = 0; i < list.size(); i++){
			PlayList playList = list.get(i);
		    // Create an Intent to launch an Activity for the tab (to be reused)
		    intent = new Intent().setClass(me, PlayListActivity.class);

		    spec = tabHost.newTabSpec(playList.getCode().toString()).setIndicator(playList.getName(), res.getDrawable((playList.getSaved() ? R.drawable.ic_menu_internet : R.drawable.ic_menu_phone))).setContent(intent);
		    tabHost.addTab(spec);
		    if(playList.getActive()){
		    	tabSelected = i;
		    }
		    tabWidget.getChildAt(i).setOnLongClickListener(this);
		}
		tabHost.setCurrentTab(tabSelected);
		tabHost.setOnTabChangedListener(this);
	}

	public boolean onLongClick(View view) {
		createContextMenu();
		return true;
	}

	private void createContextMenu(){
		final Resources res = getResources();
		final IconContextMenu iconContextMenu = new IconContextMenu(me);
		iconContextMenu.addItem(res, getText(R.string.menu_btn_new), R.drawable.ic_menu_select, 0);
		iconContextMenu.addItem(res, getText(R.string.menu_btn_edit), R.drawable.ic_menu_edit, 1);
		iconContextMenu.addItem(res, getText(R.string.menu_btn_delete), R.drawable.ic_menu_delete, 2);
		iconContextMenu.addItem(res, getText(R.string.menu_btn_share), R.drawable.ic_menu_share, 3);

		iconContextMenu.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
			public void onClick(int menuId) {
				dialog.dismiss();
				dialog = null;
				AlertDialog.Builder builder = iconContextMenu.getBuilder();
				final EditText input = new EditText(me);
				builder.setTitle(getText(R.string.alert_playlist_title));
				builder.setMessage(getText(R.string.alert_message_playlist));
				builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});
				switch (menuId) {
				case 0: // new
					builder.setView(input);
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							Editable value = input.getText();
							SongsManager.createNewPlayList(value.toString());
							PlayList playList = SongsManager.getActualPlayList();
						    // Create an Intent to launch an Activity for the tab (to be reused)
							Intent intent = new Intent().setClass(me, PlayListActivity.class);

							TabHost.TabSpec spec = getTabHost().newTabSpec(playList.getCode().toString()).setIndicator(playList.getName(), res.getDrawable((playList.getSaved() ? R.drawable.ic_menu_internet : R.drawable.ic_menu_phone))).setContent(intent);
							getTabHost().addTab(spec);
						    getTabWidget().getChildAt(SongsManager.getPlayList().size() - 1).setOnLongClickListener(me);
						}
					});
					input.setText("");
					dialog = builder.create();
					dialog.show();
					break;
				case 1: // edit
					builder.setView(input);
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							Editable value = input.getText();
							SongsManager.editPlayList(value.toString());
							setTabTitle();
						}
					});
					input.setText(SongsManager.getActualPlayList().getName());
					dialog = builder.create();
					dialog.show();
					break;
				case 2: // delete
					builder.setTitle(getText(R.string.alert_playlist_title));
					builder.setMessage(getText(R.string.alert_delete_message_playlist));
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							SongsManager.deletePlayList();
							getTabHost().getTabWidget().removeView(getTabHost().getTabWidget().getChildTabViewAt(3));
						}
					});
					dialog = builder.create();
					dialog.show();
					break;
				case 3: // share
					if(SongsManager.getActualPlayList().getSongList().size() == 0){
						Toast.makeText(me, getText(R.string.facebook_shared_empty_list), Toast.LENGTH_LONG).show();
					}
					createShareContextMenu();
				    break;
				}
			}
		});
		dialog = iconContextMenu.createMenu(getText(R.string.music_sonar_options).toString());
		dialog.show();
	}

	private void createShareContextMenu(){
		Resources res = getResources();
		final IconContextMenu iconContextMenu = new IconContextMenu(me);
		iconContextMenu.addItem(res, getText(R.string.menu_btn_my_wall), R.drawable.ic_menu_my_wall, 0);
		iconContextMenu.addItem(res, getText(R.string.menu_btn_to_friends), R.drawable.ic_menu_to_friends, 1);

		iconContextMenu.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
			public void onClick(int menuId) {
				
				switch (menuId) {
					case 0:{ // my wall
							publishList();
							break;
							}
					case 1:{ // to friends
							shareList();
						    break;
							}
				}
			}
		});
		iconContextMenu.createMenu(getText(R.string.music_sonar_options).toString()).show();
	}

	private void publishList(){
		final Bundle params = new Bundle();
        params.putString("message", getText(R.string.facebook_shared_message).toString() + " [" +  SongsManager.getActualPlayList().getName() + "] " + getText(R.string.facebook_shared_message_end).toString());
        params.putString("link", MusicSonarConstant.FACEBOOK_FEED_URL + "&list_id="+SongsManager.getActualPlayList().getCode().toString());
        params.putString("name", "MusicSonar - " + SongsManager.getActualPlayList().getName());
        params.putString("caption", "MusicSonar - " + getText(R.string.facebook_shared_caption));
        params.putString("description", MusicSonarUtils.convertToString(SongsManager.getActualPlayList().getSongList()));
        params.putString("icon", MusicSonarConstant.FACEBOOK_FEED_IMAGE);
        params.putString("type", "link");
	    MusicSonarConstant.mFacebook.dialog(me, "feed", params, new Facebook.DialogListener() {
			
			public void onFacebookError(FacebookError e) {
			}
			
			public void onError(DialogError e) {
				Toast.makeText(me, e.getMessage(), Toast.LENGTH_LONG).show();
			}
			
			public void onComplete(Bundle values) {
				String valTo = values.getString("to[0]");
				if(valTo != null){
					boolean saved = MusicSonarUtils.savePlayListOnServer();
					if(saved){
						changeTabIcon();
						Toast.makeText(me, getText(R.string.facebook_shared_ok), Toast.LENGTH_LONG).show();
					}else{
						Toast.makeText(me, getText(R.string.facebook_shared_problem), Toast.LENGTH_LONG).show();
					}
				}else{
					onCancel();
				}
			}
			
			public void onCancel() {
				Toast.makeText(me, getText(R.string.facebook_shared_cancel), Toast.LENGTH_LONG).show();
			}
		});
	}

	private void shareList(){
		final Bundle params = new Bundle();
        params.putString("message", getText(R.string.facebook_shared_message).toString() + " [" +  SongsManager.getActualPlayList().getName() + "] " + getText(R.string.facebook_shared_message_end).toString());
        params.putString("link", MusicSonarConstant.FACEBOOK_FEED_URL + "&list_id="+SongsManager.getActualPlayList().getCode().toString());
        params.putString("name", "MusicSonar - " + SongsManager.getActualPlayList().getName());
        params.putString("caption", "MusicSonar - " + getText(R.string.facebook_shared_caption));
        params.putString("description", MusicSonarUtils.convertToString(SongsManager.getActualPlayList().getSongList()));
        params.putString("icon", MusicSonarConstant.FACEBOOK_FEED_IMAGE);
        params.putString("type", "link");
	    MusicSonarConstant.mFacebook.dialog(me, "apprequests", params, new Facebook.DialogListener() {
			
			public void onFacebookError(FacebookError e) {
			}
			
			public void onError(DialogError e) {
				Toast.makeText(me, e.getMessage(), Toast.LENGTH_LONG).show();
			}
			
			public void onComplete(Bundle values) {
				String valTo = values.getString("to[0]");
				if(valTo != null){
					boolean saved = MusicSonarUtils.savePlayListOnServer();
					if(saved){
						for(int i = 0; i < 100; i ++){
							String to = values.getString("to["+i+"]");
							if(to == null){
								break;
							}

				            try {
								MusicSonarConstant.mFacebook.request(to+"/feed", params, "POST");
							} catch (Exception e) {
								Toast.makeText(me, e.getMessage(), Toast.LENGTH_LONG).show();
							}
						}
						changeTabIcon();
						Toast.makeText(me, getText(R.string.facebook_shared_ok), Toast.LENGTH_LONG).show();
					}else{
						Toast.makeText(me, getText(R.string.facebook_shared_problem), Toast.LENGTH_LONG).show();
					}
				}else{
					onCancel();
				}
			}
			
			public void onCancel() {
				Toast.makeText(me, getText(R.string.facebook_shared_cancel), Toast.LENGTH_LONG).show();
			}
		});
	}

	public void onTabChanged(String tabId) {
		TabHost tabHost = getTabHost();  // The activity TabHost
		int currentTab = tabHost.getCurrentTab();
		SongsManager.selectPlayList(currentTab);
	}

	private void setTabTitle(){
		TabHost tabHost = getTabHost();  // The activity TabHost
		int currentTab = tabHost.getCurrentTab();

		TabWidget vTabs = getTabWidget();
		RelativeLayout rLayout = (RelativeLayout) vTabs.getChildAt(currentTab);
		((TextView) rLayout.getChildAt(1)).setText(SongsManager.getPlayList(currentTab).getName());
	}

	private void changeTabIcon(){
		TabHost tabHost = getTabHost();  // The activity TabHost
		int currentTab = tabHost.getCurrentTab();

		TabWidget vTabs = getTabWidget();
		RelativeLayout rLayout = (RelativeLayout) vTabs.getChildAt(currentTab);
		((ImageView) rLayout.getChildAt(0)).setImageResource(R.drawable.ic_menu_internet);
	}

	@SuppressWarnings("unchecked")
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
        	String tabTag = getTabHost().getCurrentTabTag(); 
        	PlayListActivity activity = (PlayListActivity)getLocalActivityManager().getActivity(tabTag); 
			List<Map<String, Object>> listSelected = (List<Map<String, Object>>)data.getExtras().getSerializable("songSelected");
        	if(listSelected != null && listSelected.size() > 0){
        		for(Map<String, Object> item : listSelected){
                	if(item != null){
                		item.put("index", String.valueOf(activity.songsList.size()));
                		activity.songsList.add(item);
                	}
        		}
            	try{
            		SongsManager.savePlayList(activity.songsList);
            	}catch(Exception e){
            		e.printStackTrace();
            	}
            	ResultSearchAdapter mAdapter = new ResultSearchAdapter(this, activity.songsList, R.layout.playlist_item, new String[] { "songImage", "songTitle", "songDuration", "index", "index" }, new int[] { R.id.songImage, R.id.songTitle, R.id.songDuration, R.id.btnDeleteSong, R.id.btnPlaySong }, true);

            	activity.setListAdapter(mAdapter);
        	}
        }
    }

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		createContextMenu();
		return super.onPrepareOptionsMenu(menu);
	}
}